<template>
  <el-input v-model="area.info" class="input-with-select">
    <template #prepend>
      <el-cascader style="width: 100%;border-bottom-right-radius: 0px" :props="props" v-model="value" @change="handleChange" />
    </template>
<!--    <template #append>-->
<!--      <el-button @click="onGetCoordinate">获取经纬度</el-button>-->
<!--    </template>-->
  </el-input>

  <div style="margin-top: 10px">
    <x-map :isSearch="false" :addressClick="onAddressClick" ref="mapRef"></x-map>
  </div>
</template>

<script setup name="x-address-form">
  import XMap from './Map';
  import useStore from '@/stores/framework/area';
  const store = useStore();
  let {areaMap} = storeToRefs(store);
  const mapRef = ref(null);
  let value = ref([]);

  const area = reactive({
    province: "",
    city: "",
    area: "",
    street: "",
    village: "",
    info: "",
    lon: "",
    lat: "",
    address: "",
  })

  const props = {
    lazy: true,
    lazyLoad: async (node, resolve) => {
      resolve(await store.getAreaList(node.value));
    }
  }

  onMounted(() => {
    store.getAreaList();
  })

  const handleChange = (value) => {
    area.province = value[0];
    area.city = value[1];
    area.area = value[2];
    // area.street = value[3];
    // area.village = value[4];
    area.provinceName = areaMap.value[value[0]];
    area.cityName = areaMap.value[value[1]];
    area.areaName = areaMap.value[value[2]];
    // area.streetName = areaMap.value[value[3]];
    // area.villageName = areaMap.value[value[4]];
  }

  const onGetCoordinate = async () => {
    let address = Helper.formatAddress(area);
    console.log("获取地址" + address + "的经纬度")
    return await mapRef.value.toGetCoordinate(address);
  }

  const onAddressClick = (item, lon, lat) => {
    // console.log(item, lon, lat)
    area.lon = lon;
    area.lat = lat;
  }

  const getArea = async () => {
    if(Helper.empty(area.info)) {
      Msg.error("请输入详细地址");
      return false;
    }
    area.lon = null;
    area.lat = null;
    let {lng, lat} = await onGetCoordinate();
    area.lon = lng;
    area.lat = lat;
    if(Helper.empty(area.lon) || Helper.empty(area.lat)) {
      Msg.error("请获取经纬度信息");
      return false;
    }

    return area;
  }

  const render = (data) => {
    Helper.setReactive(area, data);
    //,data.street,data.village
    value.value = [data.province,data.city,data.area];
    setTimeout(() => {
      mapRef.value.toGetCoordinate(area.desc);
    }, 1000)
  }

  // 暴露方法
  defineExpose({
    getArea,
    render
  });
</script>

<style>
.input-with-select .el-input-group__prepend {
  background-color: #fff;
  border: none;
  padding: 0;
  margin: 0;
  width: 440px;
}
</style>
